package com.zdsoft.crm.controller;

import java.util.List;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zdsoft.crm.entity.auth.SysFunction;
import com.zdsoft.crm.entity.auth.SysUser;
import com.zdsoft.crm.service.auth.ISysFunctionService;
import com.zdsoft.crm.service.auth.ISysUserService;
import com.zdsoft.crm.vo.AjaxVo;

@Controller
public class LoginController {

	private static final Logger logger = Logger.getLogger(LoginController.class);
	
	@Autowired
	HttpSession session;

	@Autowired
	ISysUserService iSysUserService;

	@Autowired
	ISysFunctionService iSysFunctionService;

	@GetMapping("/")
	public String login() {
		
		session.setAttribute("companyName", "CRM京唐商贸");
		
		return "login.html";
	}

	@GetMapping("/a")
	public String loginq() {
		return "login.html";
	}
	
	@PostMapping("/")
	@ResponseBody // ajax提交注解@PathVariable("username") String username, @PathVariable("password") String password,
	public AjaxVo logina(@Valid SysUser user, BindingResult result) throws InterruptedException {
		
		Thread.sleep(400);
		logger.info("请求登录");
		if (result.hasErrors()) {
			for (ObjectError error : result.getAllErrors()) {
				return new AjaxVo().setErrorCode("10002").setErrorMsg(error.getDefaultMessage());
			}
		}
		SysUser dbUser = iSysUserService.findByUserName(user.getUsername());
		StandardPasswordEncoder spe = new StandardPasswordEncoder();
		List<SysFunction> FuncList;
		if (dbUser != null && spe.matches(user.getPassword(), dbUser.getPassword())) {
			// 判断分配的菜单
			if (dbUser.getIs_admin() != null && dbUser.getIs_admin().intValue() == 1) {
				FuncList = iSysFunctionService.findAll();
			} else {
				FuncList = iSysFunctionService.findByUserId(dbUser.getId());
			}
			session.setAttribute("user", dbUser);
			session.setAttribute("funcList", FuncList);
			return new AjaxVo().setErrorCode("0");
		}
		
		return new AjaxVo().setErrorCode("10002").setErrorMsg("你特么的密码错了!!!");
	}
	
	@GetMapping("/index")
	public String index() {
		return "index.html";
	}
	
	
}
